
function testStub() {
	log ('stub')
	return
	//	return;
	try {

		setTimeout(function() {
			log('notifying')
			var hints = new Object;
			//hints['x']=  300;
			//hints['y']=  300;
			//hints['sound-file'] = storage.extract("snd/inc.mp3");
			//var bus = new DBusSessionObject("org.freedesktop.DBus", "/org/freedesktop/DBus","org.freedesktop.Notifications");
			notify.launch("tes - t", "shit kører, kl. 00:00 på TV2", "http://tvtid.tv2.dk/program/index.php/id-"+1234+".html");

		/*
			bus.Notify("TVTID!",
				// UINT32	 The optional notification ID that this notification replaces (effectively modify it)
				0,
				// STRING	 The optional program icon of the calling application
				storage.extract("icon_small.png"),
				// STRING	The summary text briefly describing the notification.
				"notification",
				// STRING	The optional detailed body text. Can be empty.
				"obj.notify_title",
				// ARRAY	 Actions are sent over as a list of pairs (displayed to user)
				["action", "actiontext"], //new Array,
				//DICT	 Optional hints that can be passed to the server from the client program
				hints,
				// INT32    The timeout time in milliseconds since the display of the notification at
				// which the notification should automatically close.
				-1
				);
*/
		},3000);
	//bus.Notify("teststeset", 0, storage.extract("icon_small.png"),"title", "notification", [],{},-1)
	/*
 *var item = new ContentItem();
item.heading = "Notification Example";
item.snippet = "This is an example for a short notification.";
plugin.AddContentItem(item, gddItemDisplayAsNotification);
*/
	}catch(e) {
		log(e.message);
	}
}
var connectivity_OK;
var Reminder;
var g_Feed;
var initialized = false;
var view_refreshTimer;
var view_activeChannel;
var view_activePage;
var view_nav;
var view_maxPages = 0;
var view_curHour = 0;
var view_curDate = 0;
var view_settingsChangedTimer;
var view_lineHeight = 12;
var view_logoHeight = 21;
var view_cl1 = "<div name=\"cLogo\" x=\"1\" y=\"0\" width=\"113\" height=\"21\"></div>";
var view_cl2 = "<img width=\"114\" height=\"21\" src=\"images/backgrounds/bgLogo.png\" />";
var view_cl3 = "<img x=\"3\" y=\"0\" width=\"21\" height=\"21\" src=\"images/nav/nosignal.png\"/>";
var view_cl4 = "<img x=\"32\" y=\"0\" width=\"52\" height=\"21\" />";
var view_row1 = "<div name=\"ROWID\" " + "width=\"100%\" height=\"" + view_lineHeight + "\" " + "y=\"YPOS\"></div>";
var view_row2 = "<a name=\"pTime\" vAlign=\"middle\" width=\"25%\" height=\"" + (view_lineHeight + 1) + "\" size=\"6\" underline=\"false\" overcolor=\"#FEFEFE\" color=\"#AEAEAE\" onmouseover=\"toggleProgress(ROWID, false);\" onmouseout=\"toggleProgress(ROWID, true);\" ";
var view_row3 = "<a name=\"pTitle\" width=\"70%\" x=\"25%\" trimming=\"character\" wordWrap=\"false\" size=\"8\" height=\"" + view_lineHeight + "\" vAlign=\"middle\" underline=\"false\" overcolor=\"#FEFEFE\" color=\"#AEAEAE\" onclick=\"GetProgramDescription(CHANID,CHANINDEX);\" onmouseover=\"Reminder.guidelineShowControl(CHANID, CHANINDEX);\" onmouseout=\"Reminder.guidelineHideControl();\" ";

var view_notifier = null;
var view_notifiQueue = [];
function allow_exec() {
	return false;
	if(!options.exists("TVTID.Install.wizard_has_run")) return;

	var ok = options.getValue("TVTID.Notify.notifications_ok");
	var ask = options.getValue("TVTID.Notify.dont_ask");
log("ok:" + ok + ", ask:" + ask);
	view.onmouseover = null
	if(def(ask) && ask != "") {
		if(ok == "yes") {
alert('hier')
			notify.start();
		}
	} else {
		inst_step_notify();
	}
	

}
function view_onOptionchanged() {
	if (vverbose) {
		log(__FUNCTION());
	}
	if (/Monitor\.Programs/.test(event.propertyName)) {
		Reminder.monitor();
	} else if (!/onfly/.test(event.propertyName)) {

return
		log("Settings changed, reloading scheduled");
		if (view_settingsChangedTimer != null) {
			clearTimeout(view_settingsChangedTimer);
		}
		view_settingsChangedTimer = setTimeout(reload, 350);
	}
}
function customMenuItems(menu) {
	options.remove("TVTID.Install.wizard_has_run");
	menu.addItem(strings.l_MENUITEM_1, 0, inst_step1);
	menu.addItem(strings.l_MENUITEM_2, 0, clearAllSettings);
}
function view_onOpen() {

	pluginHelper.onAddCustomMenuItems = customMenuItems;
	view.onmouseover = allow_exec;
	if (vverbose) {
		log(__FUNCTION());
	}
	connectivity_OK = framework.system.network.online;
	view.clearInterval(view_refreshTimer);
	view_refreshTimer = view.setInterval(refreshGuide, 900000);
	initGuide();
	setTimeout(function () {
		assertCacheDir();
		cleanCacheDir();
	}, 100);
}

function view_onMinimize() {
	if (vverbose) {
		log(__FUNCTION());
	}
	view.clearInterval(view_refreshTimer);
}

function view_onRestore() {
	if (vverbose) {
		log(__FUNCTION());
	}
	view.clearInterval(view_refreshTimer);
	view_refreshTimer = view.setInterval(refreshGuide, 900000);
}

function checkOverflow() {
	if (prefs.channels.maxProgramsOnRender < 3 && prefs.channels.maxPrPage < 3) {
		if (main.scrollHeight > autosize() - 80) {
			document.getElementById("scrollIcon").style.display = "block";
		} else {
			document.getElementById("scrollIcon").style.display = "none";
		}
	}
}

function autosize() {
	if (vverbose) {
		log(__FUNCTION());
	}
	var iter = new Enumerator(view_activePage.children);
	var chanDiv;
	var pageElements = [];
	var thisIndex, i = 0;
	var totalHeight = 0;
	while (!iter.atEnd()) {
		chanDiv = iter.item();
		pageElements.push(chanDiv);
		totalHeight += chanDiv.height + 4;
		iter.moveNext();
	}
	if (totalHeight > xml_mainContainer.height) {
		resize(view.height + (totalHeight - xml_mainContainer.height));
	} else if (totalHeight < xml_mainContainer.height) {
		resize(view.height + (totalHeight - xml_mainContainer.height));
	}
}

function resize(height) {
	if (vverbose) {
		log(__FUNCTION());
	}
	var originalHeight = 300;
	var originalNavPos = 271;
	var paddingBottom = originalHeight - originalNavPos;
	view.height = height;
	xml_gfxBackground.height = height;
	xml_mainContainer.height = height - paddingBottom - 33;
	xml_gfxPageNav.y = height - paddingBottom;
	xml_gfxPageNavButton1.y = height - paddingBottom + 2;
	xml_gfxPageNavButton2.y = height - paddingBottom - 1;
	xml_gfxPageNavButton3.y = height - paddingBottom + 2;
}

function reload() {
	if (vverbose) {
		log(__FUNCTION());
	}
	view_maxPages = 0;
	initialized = false;
	view_maxPages = 0;
	view_curHour = 0;
	view_curDate = 0;
	prefs = {
		channels:{
			maxProgramsOnRender:options.getValue("TVTID.Channel.VisibleTitles") || 2,
			maxProgramsInTotal:options.getValue("TVTID.Channel.TotalTitles") || 4,
			maxPrPage:options.getValue("TVTID.Channel.TotalPrPage") || 4,
			favourites:options.getValue("TVTID.Channel.Favourites")
		},
		myChannels:[],
		hidePreviousPrograms:options.getValue("TVTID.Channel.HideCompleted")
	};

	initGuide();
}

function initGuide() {
	if (vverbose) {
		log(__FUNCTION());
	}
	xml_ajaxIcon.visible = true;
	xml_programProgress.opacity = 0.6 * gddElementMaxOpacity;
	if (typeof xml_tvguide != "undefined") {
		xml_tvguide.visible = false;
	}
	if(prefs.channels.favourites == "") {
		prefs.myChannels = ["DR1", "TV 2", "TV3"];
	} else
		prefs.myChannels = prefs.channels.favourites.split(",");
	if (prefs.myChannels.length == 0) {
		g_useDefaultChannels = true;
	}
	if (view_curHour == 0) {
		var a = new Date;
		setTimeInterval(a.getDate(), a.getHours());
	} else if (view_curHour != 23 && view_curHour + 1 == (new Date).getHours()) {
		setTimeInterval(view_curDate, ++view_curHour);
	} else {
		setTimeInterval(view_curDate, view_curHour);
	}
	view_activePage = xml_chanPage_0;
	autosize();
	view_activePage.visible = true;
	xml_tvguide.visible = true;
	var str = "";
	var el = view_activePage;
	Reminder = Favourites.init();
}

function toggleHidePreviousPrograms() {
	prefs.hidePreviousPrograms = !prefs.hidePreviousPrograms;
	refreshGuide();
}

function setTimeInterval(d, h) {
	if (vverbose) {
		log(__FUNCTION());
	}
	try {
		var a = new Date;
		view_curDate = d;
		view_curHour = h;
		a.setDate(d);
		a.setHours(h, 0, 0, 0);
		var from = Math.floor(a.getTime() / 1000);
		options.putValue("TVTID.onfly.from", from);
		if ((new Date).getHours() == h) {
			xml_navNowButton.image = "images/nav/now.png";
			xml_navNowButton.onclick = toggleHidePreviousPrograms;
			xml_navNowButton.caption = "";
			xml_navNowButton.tooltip = prefs.hidePreviousPrograms ? strings.NAVFILTER_IS_ON : strings.NAVFILTER_IS_OFF;
		} else {
			xml_navNowButton.image = "images/transparent.gif";
			xml_navNowButton.caption = h + ".00";
			xml_navNowButton.onclick = function () {};

			xml_navNowButton.tooltip = "";
		}
		updateFeed();
	} catch (e) {
		e.message = "@setTimeInterval:\n" + e.message;
		throw e;
	}
}

function lookaheadFeed() {
	if (vverbose) {
		log(__FUNCTION());
	}
	var a = new Date;
	var d = view_curDate;
	var h = view_curHour + 1;
	a.setDate(d);
	a.setHours(h, 0, 0, 0);
	var from = Math.floor(a.getTime() / 1000);
	var oldFrom = options.getValue("TVTID.onfly.from");
	var oldFeed = g_Feed;
	options.putValue("TVTID.onfly.from", from);
	getFeed();
	var lookahead_feed = g_Feed;
	g_Feed = oldFeed;
	options.putValue("TVTID.onfly.from", oldFrom);
	return lookahead_feed;
}

function updateFeed() {
	if (vverbose) {
		log(__FUNCTION());
	}
	var oldActivePage = view_activePage ? view_activePage.name : false;
	try {
		if (connectivity_OK && view_curHour == 2) {
			var cheat = lookaheadFeed();
		}
		log("(" + options.getValue("TVTID.onfly.from") + ") " + view_curHour + ".00 opdaterer");
		getFeed();
		log("done - har " + g_Feed.channels.length + " channels");
		xml_tvguide.removeAllElements();
		view_maxPages = 0;
		var i = 0, active = 0;
		if (prefs.myChannels.length > 0) {
			prefs.myChannels.forEach(function (trueChanId) {
				i = getIndex(trueChanId, true);
				if (active++ % prefs.channels.maxPrPage == 0) {
					appendChanPage();
					g_offsetHeight = 0;
				}
				if (g_Feed.channels[i].program.length == 0 && cheat) {
					createChanElement(cheat.channels[i], i);
				} else {
					createChanElement(g_Feed.channels[i], i);
				}
			});
		} else {
			g_Feed.channels.forEach(function (channel) {
				if (isSubscribed(channel.name, channel.id)) {
					if (active++ % prefs.channels.maxPrPage == 0) {
						appendChanPage();
						g_offsetHeight = 0;
					}
					if (channel.program.length == 0 && cheat) {
						createChanElement(cheat.channels[i], i);
					} else {
						createChanElement(channel, i);
					}
				}
				i++;
			});
		}
		if (oldActivePage) {
			xml_chanPage_0.visible = false;
			view_activePage = eval(oldActivePage);
			view_activePage.visible = true;
		} else {
			view_activePage = xml_chanPage_0;
		}
		xml_ajaxIcon.visible = false;
		if (vverbose) {
			log("-->" + true);
		}
		return true;
	} catch (e) {
		e.message = "@updateFeed:\n" + e.message;
		throw e;
	}
	if (vverbose) {
		log("-->" + false);
	}
}

function appendChanPage() {
	if (vverbose) {
		log(__FUNCTION());
	}
	try {
		var existing = eval("xml_chanPage_" + view_maxPages);
	} catch (ign) {}
	if (typeof existing != "undefined") {
		existing.parentElement.removeElement(existing);
	}
	view_activePage = xml_tvguide.appendElement("<div width=\"100%\" height=\"100%\" name=\"xml_chanPage_" + view_maxPages + "\" " + (view_maxPages++ != 0 ? "visible=\"false\"" : "") + "></div>");
	if (vverbose) {
		log("-->" + "xml_chanPage_" + view_maxPages);
	}
}

function refreshGuide() {
	if (vverbose) {
		log(__FUNCTION());
	}
	connectivity_OK = framework.system.network.online;
	try {
		if (view_curHour == 0) {
			var a = new Date;
			setTimeInterval(a.getDate(), a.getHours());
		} else if (view_curHour != 23 && view_curHour + 1 == (new Date).getHours()) {
			setTimeInterval(view_curDate, ++view_curHour);
		} else {
			setTimeInterval(view_curDate, view_curHour);
		}
	} catch (e) {
		e.message = "@refreshGuide:\n" + e.message;
		throw e;
	}
}
var g_offsetHeight = 0;
function flipPage(dir) {
	if (vverbose) {
		log(__FUNCTION());
	}
	var cur = parseInt(view_activePage.name.replace(/[^0-9]*/, ""));
	if (cur == 0 && dir < 0) {
		return;
	} else if (view_maxPages == cur + 1 && dir > 0) {
		return;
	}
	view_activePage.visible = false;
	view_activePage = eval("xml_chanPage_" + (cur + dir));
	view_activePage.visible = true;
	if (typeof addremove != "undefined") {
		addremove.visible = false;
	}
}

function switchInterval(dir) {
	if (vverbose) {
		log(__FUNCTION());
	}
	var from = options.getValue("TVTID.onfly.from");
	from = from * 1000;
	from = from + dir * 60 * 60 * 1000;
	var d = new Date(from);
	try {
		setTimeInterval(d.getDate(), d.getHours());
	} catch (e) {
		log(e.message);
		initialized = false;
		initGuide();
	}
	if (vverbose) {
		log("--> ok");
	}
}

function createChanLogo(page, chan, active) {
	if (vvverbose) {
		log(__FUNCTION());
	}
	var el = page.appendElement(view_cl1);
	el.appendElement(view_cl2);
	if (!active) {
		el.appendElement(view_cl3);
	}
	var img = el.appendElement(view_cl4);
	loadImageStream("http://tvtid.tv2.dk" + chan.logo, function (stream) {
		try {
			img.src = stream;
		} catch (e) {
			log("img load error" + chan.logo);
		}
	});
	return el;
}

function createChanElement(chan, chanID) {
	if (vvverbose) {
		log(__FUNCTION());
	}
	try {
		var visibleheight = view_lineHeight * prefs.channels.maxProgramsOnRender + view_logoHeight, ypos = view_logoHeight;
		var guide = view_activePage, title, titletip, mangledID = mangleChanId(chan.name);
		guide = guide.appendElement("<div name=\"" + mangledID + "\" x=\"0\" y=\"" + g_offsetHeight + "\" " + "width=\"100%\" height=\"" + visibleheight + "\"></div>");
		var row, rowId, title, cell, now = new Date;
		if (chan.program.length == 0) {
			createChanLogo(guide, chan);
			return false;
		}
		for (var i = 0, visible = 0, skipped = 0; i < chan.program.length; i++) {
			if (i == 0) {
				createChanLogo(guide, chan, true);
				gfxX.create(guide, chan);
			}
			if (!chan.program[i] && ++skipped) {
				continue;
			} else if (view_curHour == now.getHours() && prefs.hidePreviousPrograms && now > new Date(chan.program[i].end_timestamp * 1000) && ++skipped) {
				if (i < prefs.channels.maxProgramsInTotal) {
					continue;
				} else if (visible != 0 || chan.program.length < i + 1) {
					continue;
				}
				--skipped;
			}
			rowId = "d_chan" + chanID + "_prog" + i;
			row = guide.appendElement(view_row1.replace(/ROWID/g, rowId).replace(/YPOS/g, ypos));
			title = mangleEntities(chan.program[i].title);
			titletip = title + mangleEntities(chan.program[i].short_description != "" ? " - " + chan.program[i].short_description : "");
			cell = row.appendElement(view_row2.replace(/ROWID/g, rowId) + "tooltip=\"" + chan.program[i].start + "-" + chan.program[i].end + "\">" + chan.program[i].start + "</a>");
			cell = row.appendElement(view_row3.replace(/CHANID/g, chanID).replace(/CHANINDEX/g, i) + "tooltip=\"" + titletip + "\">" + title + "</a>");
			ypos += view_lineHeight;
			visible++;
		}
	} catch (e) {
		log("@createChanElement: " + e.message);
	} finally {
		g_offsetHeight += prefs.channels.maxProgramsOnRender * view_lineHeight + 21 + 4;
		if (visible > 0) {
			return true;
		} else {
			return false;
		}
	}
}
var prog_sliderElement, prog_playWidth, prog_fulltimeWidth, prog_count, prog_paintTimer, prog_hidePaintTimer;
function paintProgress() {
	if (prog_playWidth > prog_count) {
		xml_programProgress.value = prog_count;
		prog_paintTimer = setTimeout(paintProgress, 10 + prog_count);
	}
	prog_count++;
}

function toggleProgress(element, doHide) {
	if (vvverbose) {
		log(__FUNCTION());
	}
	var bar = xml_programProgress;
	if (prog_paintTimer != null) {
		clearTimeout(prog_paintTimer);
	}
	if (prog_hidePaintTimer != null) {
		clearTimeout(prog_hidePaintTimer);
	}
	if (doHide) {
		prog_hidePaintTimer = setTimeout(function () {
			bar.visible = false;
			prog_sliderElement = prog_playWidth = prog_count = prog_paintTimer = null;
		}, 600);
		return;
	}
	var id = element.name.replace(/d_chan([^_]*).*/, "$1");
	var prog = element.name.replace(/.*prog/, "");
	var now = Math.floor((new Date).getTime() / 1000);
	if (typeof g_Feed.channels[id].program[prog] == "undefined") {
		element.children.item("pTime").tooltip = "Mangelfulde data";
		return;
	}
	var bStamp = g_Feed.channels[id].program[prog].start_timestamp;
	var eStamp = g_Feed.channels[id].program[prog].end_timestamp;
	prog_fulltimeWidth = Math.floor((eStamp - bStamp) / 60);
	prog_playWidth = Math.floor((now - bStamp) / 60);
	var pos = findPos(element);
	bar.y = pos.y - 18;
	bar.value = 0;
	bar.visible = true;
	bar.min = 0;
	bar.max = prog_fulltimeWidth;
	prog_count = 0;
	if (now >= bStamp) {
		setTimeout(paintProgress, 25);
	}
}
